package com.atguigu.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class Flink01_Batch_WordCount {
    public static void main(String[] args) throws Exception {
        /**
         * spark中WordCount求法：
         * 1.创建spark环境
         * 2.读取文件数据 textFile
         * 3.按照空格切分出每一个单词 flatmap
         * 4.将每一个单词转为Tuple2元组<单词（String），1（Integer）> mapTopair
         * 5.将相同单词的数据聚合到一块 reducebykey
         * 6.累加
         */

        //1.创建flink批处理环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //2.读取文件数据
        DataSource<String> dataSource = env.readTextFile("input/word.txt");

        //3.按照空格切出每一个单词
        FlatMapOperator<String, String> words = dataSource.flatMap(new MyflatMap());

        //4.将每一个单词转为Tuple2元组<单词（String），1（Integer）>
        MapOperator<String, Tuple2<String, Integer>> wordToOne = words.map(new MapFunction<String, Tuple2<String, Integer>>() {
            /**
             *
             * @param value 接收到的每一个单词
             * @return
             * @throws Exception
             */
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
//                return new Tuple2<>(value, 1);
                return Tuple2.of(value, 1);
            }
        });

        //5.将相同的单词集合到一块
        UnsortedGrouping<Tuple2<String, Integer>> groupBy = wordToOne.groupBy(0);

        //6.累加
        AggregateOperator<Tuple2<String, Integer>> result = groupBy.sum(1);

        result.print();
    }

    public static class MyflatMap implements FlatMapFunction<String,String>{

        /**
         *
         * @param value 接受传进来的数据
         * @param out 收集器 用来接受返回的数据并发送给下游
         * @throws Exception
         */
        @Override
        public void flatMap(String value, Collector<String> out) throws Exception {
            //按照空格切分数据
            String[] words = value.split(" ");
            //遍历数据获取到每一个单词
            for (String word : words) {
                out.collect(word);
            }
        }
    }
}
